﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using Lucene.Net.Documents;
using CommonSearchModule;
using System.Data.SqlClient;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Index;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;

namespace CreateIndexFile
{
    public class SearchVKeChengIndexFile : IndexFileBase
    {
        public SearchVKeChengIndexFile()
            : base(ConfigurationManager.AppSettings["VKeCheng_IndexDocumentsPath"])
        { }

        #region Public Methods

        public override void Create()
        {
            writer.SetMaxBufferedDocs(10);
            Stopwatch watch = new Stopwatch();
            watch.Start();
            StringBuilder sb;
            using (SqlConnection conn = new SqlConnection(connString))
            {
                sb = new StringBuilder();
                SqlCommand comm = new SqlCommand();
                comm.CommandTimeout = 0;
                comm.Connection = conn;
                sb.Append(@"     
 


CREATE TABLE #Temp_Item
    (
      ItemID INT ,
      ItemName NVARCHAR(500),
      PropertyName NVARCHAR(max),--所有属性名称
      ChildItemName NVARCHAR(max),--所有子包名称
      MinPrice DECIMAL(10,2),--最小价格
      MaxPrice DECIMAL(10,2),--最大价格
      PropertyInfo NVARCHAR(max),--年级名称
      Picture NVARCHAR(500)--图片
    );
DECLARE @ItemID INT,@ItemName NVARCHAR(500),@PropertyName NVARCHAR(max),@ChildItemName NVARCHAR(max),@PropertyInfo NVARCHAR(max),@Picture NVARCHAR(500);
DECLARE @TempTwoVID INT;

DECLARE @MinPrice DECIMAL(10,2),@maxPrice DECIMAL(10,2);
--所有微课程二级包
DECLARE cursor_item CURSOR FOR
	SELECT i.ID,Name,Picture FROM dbo.Res_Item i
	INNER JOIN(SELECT distinct itemid FROM dbo.Res_ItemCategory WHERE ValueID=5506)ic ON i.ID=ic.ItemID;
--打开游标
OPEN cursor_item;
FETCH NEXT FROM cursor_item INTO @ItemID,@ItemName,@Picture;
WHILE @@fetch_status = 0           --判断是否成功获取数据
   BEGIN
	--查询包属性
	SET @PropertyName = '';
	SET @PropertyInfo = '';
	SELECT @PropertyName=@PropertyName + bpv.Name+'|',@PropertyInfo=@PropertyInfo+'[vid='+LTRIM(STR(bpv.VID))+',pid='+LTRIM(STR(bpv.PID))+']'+bpv.Name+'|' FROM
	(SELECT * FROM dbo.Res_ItemCategory WHERE ItemID=@ItemID)ic
	INNER JOIN dbo.Common_BasePropValue bpv ON ic.ValueID = bpv.VID;
	---------------------查询子包---------------------
	--查询二级知识点包
	SELECT @TempTwoVID = bpv.VID FROM
	(SELECT * FROM dbo.Res_ItemCategory WHERE ItemID=@ItemID)ic
	INNER JOIN (SELECT VID FROM dbo.Common_BasePropValue WHERE PID=32) bpv ON ic.ValueID = bpv.VID;
	--查询试题类型包
	SET @ChildItemName = '';
	SELECT @ChildItemName=@ChildItemName+i.Name+'|' FROM
	(SELECT DISTINCT ItemID FROM dbo.Res_ItemCategory WHERE ValueID=5507)icThree
	INNER JOIN(SELECT DISTINCT ItemID FROM dbo.Res_ItemCategory WHERE ValueID=@TempTwoVID)icTwo ON icThree.ItemID = icTwo.ItemID
	INNER JOIN dbo.Res_Item i ON icThree.ItemID =i.ID
	---------------------------查询包价格---------------------
	SET @maxPrice = 0;
	SET @MinPrice = 0;
	SELECT @maxPrice= MAX(MaxPrice) FROM dbo.Res_ItemPrice WHERE ItemID = @ItemID;
	
	SELECT @MinPrice= MIN(MaxPrice) FROM 
	(SELECT DISTINCT ItemID FROM dbo.Res_ItemCategory WHERE ValueID=5507)icThree
	INNER JOIN(SELECT DISTINCT ItemID FROM dbo.Res_ItemCategory WHERE ValueID=@TempTwoVID)icTwo ON icThree.ItemID = icTwo.ItemID
	INNER JOIN dbo.Res_Item i ON icThree.ItemID =i.ID
	INNER JOIN dbo.Res_ItemPrice price ON icThree.ItemID = price.ItemID
	
   -------------------写入数据-------------------
	INSERT INTO #Temp_Item
	        ( 
              ItemID ,
	          ItemName ,
	          PropertyName ,
	          ChildItemName,
	          MinPrice,
	          MaxPrice,
	          PropertyInfo,
	          Picture
	        )
	VALUES  (
               @ItemID ,
	          @ItemName ,
	          @PropertyName ,
	          @ChildItemName ,
	          @MinPrice,
	          @maxPrice,
	          @PropertyInfo,
	          @Picture
	        )
	FETCH NEXT FROM cursor_item INTO @ItemID,@ItemName,@Picture;
END
--关闭释放游标
CLOSE cursor_item;
DEALLOCATE cursor_item;

SELECT distinct 'VKeCheng'+LTRIM(STR(ItemID)) as PrimaryKey, ItemID AS ID,ItemName AS Name,MinPrice AS ExtentionField1,MaxPrice AS ExtentionField2,PropertyName AS PropertyName,ChildItemName AS ExtentionField3,PropertyInfo AS ExtentionField4,Picture AS ExtentionField5 FROM #Temp_Item;


DROP TABLE #Temp_Item;

 ");
                comm.CommandText = sb.ToString();
                conn.Open();
                SqlDataReader reader = comm.ExecuteReader();

                int rowCount = 1;
                try
                {
                    while (reader.Read())
                    {
                        Search_Entity entity = new Search_Entity();
                        entity.ID = reader["id"].ToString();
                        entity.Name = Regex.Replace(reader["Name"].ToString(), @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase);
                        entity.PropertyName = reader["PropertyName"].ToString();
                        entity.ExtentionField1 = reader["ExtentionField1"].ToString();
                        entity.ExtentionField2 = reader["ExtentionField2"].ToString();
                        entity.ExtentionField3 = reader["ExtentionField3"].ToString();
                        entity.ExtentionField4 = reader["ExtentionField4"].ToString();
                        entity.ExtentionField5 = reader["ExtentionField5"].ToString();
                        //添加到索引
                        Document doc = InitDocument(entity);

                        writer.AddDocument(doc);
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine("执行次数：" + rowCount++.ToString());
                        Console.WriteLine("执行时间：" + watch.Elapsed.ToString());
                    }
                }
                finally
                {
                    reader.Close();
                }
            }

            writer.Optimize();
            writer.Close();

            TimeSpan _RunTime = new TimeSpan(DateTime.Now.Ticks);
            TimeSpan _RunTime2 = new TimeSpan(DateTime.Now.AddDays(-2).Ticks);
            TimeSpan ss = _RunTime.Subtract(_RunTime2);
            Console.WriteLine(ss.Hours);

            SetCreatePath();
        }

        #endregion Public Methods

        #region Private Methods

        /// <summary>
        /// 初始化Document流中的字段field
        /// Field.Index 	Field.Store 	说明
        /// TOKENIZED（分词） 	YES 	被分词索引且存储
        /// TOKENIZED 	        NO 	被分词索引但不存储
        /// NO 	                YES 	这是不克不及被搜刮的，它只是被搜刮内容的从属物。如URL等
        /// UN_TOKENIZED 	    YES/NO 	不被分词，它作为一个整体被搜刮，搜一项目组是搜不出来的
        /// NO 	                NO 	没有这种用法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        protected override Document InitDocument(Search_Entity entity)
        {
            Document doc = new Document();

            doc.Add(new Field(FieldKeys.ID, entity.ID.ToString(), Field.Store.YES, Field.Index.NO));
            doc.Add(new Field(FieldKeys.Name, entity.Name, Field.Store.YES, Field.Index.TOKENIZED));
            if (!string.IsNullOrEmpty(entity.ExtentionField1))
                doc.Add(new Field(FieldKeys.ExtentionField1, entity.ExtentionField1, Field.Store.YES, Field.Index.TOKENIZED));
            if (!string.IsNullOrEmpty(entity.ExtentionField2))
                doc.Add(new Field(FieldKeys.ExtentionField2, entity.ExtentionField2, Field.Store.YES, Field.Index.TOKENIZED));
            if (!string.IsNullOrEmpty(entity.ExtentionField3))
                doc.Add(new Field(FieldKeys.ExtentionField3, entity.ExtentionField3, Field.Store.YES, Field.Index.TOKENIZED));
            if (!string.IsNullOrEmpty(entity.ExtentionField4))
                doc.Add(new Field(FieldKeys.ExtentionField4, entity.ExtentionField4, Field.Store.YES, Field.Index.TOKENIZED));
            if (!string.IsNullOrEmpty(entity.ExtentionField5))
                doc.Add(new Field(FieldKeys.ExtentionField5, entity.ExtentionField5, Field.Store.YES, Field.Index.TOKENIZED));
            doc.Add(new Field(FieldKeys.SearchKey, "key", Field.Store.NO, Field.Index.UN_TOKENIZED));
            return doc;
        }
        #endregion Private Methods
    }
}
